package drawer

import (
	"MetroBuilderGameJam/gameEngine/geom"
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"github.com/hajimehoshi/ebiten/v2/vector"
	"image/color"
)

func NewDrawer(anchor FigureAnchor) *Drawer {
	return &Drawer{
		Anchor: anchor,
	}
}

func NewCentralDrawer() *Drawer {
	return &Drawer{
		Anchor: AnchorCenter,
	}
}

type Drawer struct {
	Offset     geom.Point
	Anchor     FigureAnchor
	PivotWidth uint8
}

func (d *Drawer) preparePathToDraw(path vector.Path, w float64, clr color.Color) (vs []ebiten.Vertex, is []uint16, op *ebiten.DrawTrianglesOptions) {
	so := &vector.StrokeOptions{}
	so.Width = float32(w)
	vs, is = path.AppendVerticesAndIndicesForStroke(nil, nil, so)
	vs = setColorToVertices(vs, clr)
	op = &ebiten.DrawTrianglesOptions{}
	op.AntiAlias = false
	op.FillRule = ebiten.NonZero
	op.ColorScaleMode = ebiten.ColorScaleModeStraightAlpha

	return vs, is, op
}

func (d *Drawer) preparePathToFill(path vector.Path, clr color.Color) (vs []ebiten.Vertex, is []uint16, op *ebiten.DrawTrianglesOptions) {
	vs, is = path.AppendVerticesAndIndicesForFilling(nil, nil)
	vs = setColorToVertices(vs, clr)
	op = &ebiten.DrawTrianglesOptions{}
	op.AntiAlias = false
	op.FillRule = ebiten.NonZero
	op.ColorScaleMode = ebiten.ColorScaleModeStraightAlpha

	return vs, is, op
}

func (d *Drawer) drawPath(dst *ebiten.Image, vs []ebiten.Vertex, is []uint16, op *ebiten.DrawTrianglesOptions) {
	dst.DrawTriangles(vs, is, whiteSubImage, op)
}

func (d *Drawer) drawPivot(dst *ebiten.Image, pos geom.Point, clr color.Color) {
	if d.PivotWidth > 0 {
		d.Point(dst, pos, float64(d.PivotWidth), clr)
	}
}

func (d *Drawer) GetRectanglePoints(pivot geom.Point, size geom.Size, rotation geom.Radian) (geom.Vec2F32, geom.Vec2F32, geom.Vec2F32, geom.Vec2F32) {
	offset := d.applyAnchor(d.Offset.AsVec2().Add(pivot.AsVec2()), size)

	p1 := geom.NewVec2(offset.X-size.Width, offset.Y-size.Height).RotateAround(rotation, pivot.AsVec2()).ToVec2F32()
	p2 := geom.NewVec2(offset.X+size.Width, offset.Y-size.Height).RotateAround(rotation, pivot.AsVec2()).ToVec2F32()
	p3 := geom.NewVec2(offset.X+size.Width, offset.Y+size.Height).RotateAround(rotation, pivot.AsVec2()).ToVec2F32()
	p4 := geom.NewVec2(offset.X-size.Width, offset.Y+size.Height).RotateAround(rotation, pivot.AsVec2()).ToVec2F32()

	return p1, p2, p3, p4
}

func (d *Drawer) SimpleRectangleToDrawed(point geom.Point, size geom.Size) (geom.Point, geom.Size) {
	p1, p2, p3, _ := d.GetRectanglePoints(point, size, 0)
	return p1.ToVec2().AsPoint(), geom.Size{Width: float64(p2.X - p1.X), Height: float64(p3.Y - p1.Y)}
}

func (d *Drawer) Text(screen *ebiten.Image, text string, point geom.Point, _ color.Color) {
	p := point.AsVec2().Sub(geom.NewVec2(4, 8)).AsPoint().ToIntPoint()
	ebitenutil.DebugPrintAt(screen, text, p.X, p.Y)
}
